package com.davies.learn.jbv.controller;



import com.davies.learn.jbv.domain.dto.ErrorResponseDTO;
import com.google.common.base.Strings;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.stream.Collectors;

/**
 * @author davies
 * @date 2022/2/19 1:48 PM
 */
@ControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<ErrorResponseDTO> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(new ErrorResponseDTO(HttpStatus.INTERNAL_SERVER_ERROR.name()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = {ConstraintViolationException.class})
    public ResponseEntity<ErrorResponseDTO> constraintViolationException(ConstraintViolationException e) {
        String message = e.getMessage();
        return new ResponseEntity<>(new ErrorResponseDTO(HttpStatus.BAD_REQUEST.name(), message,null), HttpStatus.BAD_REQUEST);
    }

    /**
     * 参数验证错误
     *
     * @param e MethodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity<ErrorResponseDTO> methodArgumentNotValid(MethodArgumentNotValidException e) {
        ErrorResponseDTO response;
        if (e.hasFieldErrors()) {
            String message = e.getFieldErrors()
                    .stream()
                    .map(this::fieldErrorToMessage)
                    .collect(Collectors.joining("\n"));
            response = new ErrorResponseDTO(HttpStatus.BAD_REQUEST.name(), message,null);
        } else {
            response = new ErrorResponseDTO();
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
    private String fieldErrorToMessage(FieldError fieldError){
        return Strings.lenientFormat("[%s]%s",
                fieldError.getField(),
                fieldError.getDefaultMessage());
    }


}
